package com.bto.solar.work.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.EnumUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.bto.solar.work.common.BizException;
import com.bto.solar.work.config.WrappersFactory;
import com.bto.solar.work.constant.BizStageEnum;
import com.bto.solar.work.constant.BizTaskEnum;
import com.bto.solar.work.constant.BizTaskStateEnum;
import com.bto.solar.work.constant.Constants;
import com.bto.solar.work.constant.DBConstants;
import com.bto.solar.work.constant.EditAndApprovalEnum;
import com.bto.solar.work.dao.IAppointService;
import com.bto.solar.work.dao.ICompanyService;
import com.bto.solar.work.dao.IConstructService;
import com.bto.solar.work.dao.ICustomerService;
import com.bto.solar.work.dao.IDesignService;
import com.bto.solar.work.dao.IDeviceService;
import com.bto.solar.work.dao.IGridConnectionService;
import com.bto.solar.work.dao.IInsuranceService;
import com.bto.solar.work.dao.ILeaseLessorService;
import com.bto.solar.work.dao.ILeasePrjProjectProductService;
import com.bto.solar.work.dao.ILeaseReviewService;
import com.bto.solar.work.dao.IOrderBaseService;
import com.bto.solar.work.dao.IOrderOperationLogService;
import com.bto.solar.work.dao.IOrderStateService;
import com.bto.solar.work.dao.IReconnoitreService;
import com.bto.solar.work.dao.IRecordService;
import com.bto.solar.work.dao.ISettlementService;
import com.bto.solar.work.dao.IUserSearchRecordService;
import com.bto.solar.work.dto.ApprovalReq;
import com.bto.solar.work.dto.CheckDeviceValidRes;
import com.bto.solar.work.dto.FormBtnsDto;
import com.bto.solar.work.dto.QueryCusEarningsReq;
import com.bto.solar.work.dto.lease.OperatingFarmGinsReqBody;
import com.bto.solar.work.dto.lease.OperatingFarmGinsRes;
import com.bto.solar.work.dto.order.ConstructDto;
import com.bto.solar.work.dto.order.ConstructSGXXDto;
import com.bto.solar.work.dto.order.CreateOrderReq;
import com.bto.solar.work.dto.order.CustomerInfoDto;
import com.bto.solar.work.dto.order.DesignDto;
import com.bto.solar.work.dto.order.DeviceDto;
import com.bto.solar.work.dto.order.GSContractDto;
import com.bto.solar.work.dto.order.LeaseContractDto;
import com.bto.solar.work.dto.order.OrderGridDto;
import com.bto.solar.work.dto.order.OrderLogReq;
import com.bto.solar.work.dto.order.PreApprovalDto;
import com.bto.solar.work.dto.order.QueryOrderReq;
import com.bto.solar.work.dto.order.QueryOrderRes;
import com.bto.solar.work.dto.order.RecordDto;
import com.bto.solar.work.dto.order.SettlementDto;
import com.bto.solar.work.dto.order.TaKanDto;
import com.bto.solar.work.dto.order.TecKanChaDto;
import com.bto.solar.work.entity.Appoint;
import com.bto.solar.work.entity.Company;
import com.bto.solar.work.entity.Construct;
import com.bto.solar.work.entity.Customer;
import com.bto.solar.work.entity.Design;
import com.bto.solar.work.entity.Device;
import com.bto.solar.work.entity.GridConnection;
import com.bto.solar.work.entity.Insurance;
import com.bto.solar.work.entity.LeaseLessor;
import com.bto.solar.work.entity.LeasePrjProjectProduct;
import com.bto.solar.work.entity.LeaseReview;
import com.bto.solar.work.entity.OrderBase;
import com.bto.solar.work.entity.OrderOperationLog;
import com.bto.solar.work.entity.OrderState;
import com.bto.solar.work.entity.Reconnoitre;
import com.bto.solar.work.entity.Record;
import com.bto.solar.work.entity.Settlement;
import com.bto.solar.work.entity.User;
import com.bto.solar.work.entity.UserSearchRecord;
import com.bto.solar.work.lease.LeaseApi;
import com.bto.solar.work.service.biz_stage_handler.DesignStageHandler;
import com.bto.solar.work.service.biz_stage_handler.LeaseSyncProjectHandler;
import com.bto.solar.work.service.biz_stage_handler.StageHandlerFactory;
import com.bto.solar.work.utils.BeanUtils;
import com.bto.solar.work.utils.DateUtils;
import com.bto.solar.work.utils.IdUtils;
import com.bto.solar.work.utils.NullUtils;
import com.bto.solar.work.utils.StringUtils;
import com.bto.solar.work.vo.DeviceVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author 王小波
 * @description: 订单相关的服务
 * @date 2023/7/12 9:27
 */

@Slf4j
@Service
public class BtoOrderService {
    @Autowired
    private ICustomerService customerService;
    @Autowired
    private IOrderBaseService orderService;
    @Autowired
    private IReconnoitreService reconnoitreService;
    @Autowired
    private IDesignService designService;
    @Autowired
    private IOrderStateService orderStateService;
    @Autowired
    private IConstructService constructService;
    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private IRecordService recordService;
    @Autowired
    private ILeasePrjProjectProductService leasePrjProjectProductService;
    @Autowired
    private IGridConnectionService gridConnectionService;
    @Autowired
    private ISettlementService settlementService;
    @Autowired
    private IInsuranceService insuranceService;
    @Autowired
    private IUserSearchRecordService userSearchRecordService;
    @Autowired
    private ICompanyService companyService;
    @Autowired
    private IAppointService appointService;
    @Autowired
    private IOrderOperationLogService orderOperationLogService;

    @Autowired
    private BtoOperateLogService optLog;

    @Autowired
    private BtoOrderStateService btoOrderStateService;
    @Autowired
    private BtoLeaseReviewService btoLeaseReviewService;
    @Autowired
    @Lazy
    private ILeaseReviewService leaseReviewService;
    @Autowired
    private ILeaseLessorService leaseLessorService;

    @Autowired
    private LeaseSyncProjectHandler leaseSyncProjectHandler;
    @Autowired
    private BtoUserService btoUserService;

    @Autowired
    private BtoStoImportService btoStoImportService;
    @Autowired
    private BtoOrderOperateLogService btoOrderOperateLogService;
    @Autowired
    private BtoDeviceService btoDeviceService;
    @Autowired
    private BtoDesignService btoDesignService;
    @Autowired
    private BtoRecordService btoRecordService;

    @Autowired
    @Lazy
    private LeaseApi leaseApi;
    @Autowired
    private StageHandlerFactory stageHandlerFactory;

    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private TransactionTemplate transactionTemplate;
    @Autowired
    private WrappersFactory wrappersFactory;


    /**
     * 数据提交
     * type : SAVE、APPROVAL
     */
    public void dataSubmit(String orderId, String stageId, String taskId, Object data) {
        val handler = stageHandlerFactory.getLeaseStageHandlerByStatusId(stageId);
        handler.dataSubmit(orderId, stageId, taskId, data);
    }


    /**
     * 提交审批
     */
    public String updateToWaitingApprovalState(String orderId, String stageId, String taskId) {
        val handler = stageHandlerFactory.getLeaseStageHandlerByStatusId(stageId);
        handler.updateToWaitingApprovalState(orderId, stageId, taskId);
        return btoOrderStateService.getOrderTaskState(orderId, stageId, taskId).getStateId();
    }


    /**
     * 创建新的业务订单
     */
    @Transactional(rollbackFor = Exception.class)
    public OrderBase createNewOrder(CreateOrderReq createOrderReq) {
        String usIdCarNo = createOrderReq.getIdNumber();
        String phoneNum = createOrderReq.getPhone();
//        ValidUtils.isIdCardNum(usIdCarNo);
//        ValidUtils.isPhoneNum(phoneNum);

        OrderBase orderBase = new OrderBase();
        orderBase.setOrderId(generateOrderNo());
        orderBase.setName(createOrderReq.getName());
        //设置订单公司id
        orderBase.setCompanyId(btoUserService.getCurrentUserCompany().getCompanyId());
        orderBase.setUserId(btoUserService.getCurrentUser().getUserId());
        orderBase.setType(createOrderReq.getType());
//        orderBase.setLat(createOrderReq.getLat());
//        orderBase.setLng(createOrderReq.getLng());
//        orderBase.setProvinceCode(createOrderReq.getProvinceCode());
//        orderBase.setCityCode(createOrderReq.getCityCode());
//        orderBase.setAreaCode(createOrderReq.getAreaCode());
//        orderBase.setInstallationAddress(createOrderReq.getInstallationAddress());
//        orderBase.setDetailedAddress(createOrderReq.getDetailedAddress());


        //一个订一个客户信息（存在重复的身份证号码）
        Customer customer = new Customer();
        customer.setCustomerId(IdUtils.fastSnowId());

        customer.setCompanyId(orderBase.getCompanyId());
        customer.setName(createOrderReq.getName());
        customer.setDdCustomerType(createOrderReq.getDdCustomerType());
        customer.setIdCardType(createOrderReq.getIdCardType());
        customer.setIdNumber(createOrderReq.getIdNumber());
        customer.setPhone(createOrderReq.getPhone());

        //复制之前客户信息的身份证信息
        List<Customer> customers = customerService.lambdaQuery()
                .eq(Customer::getIdNumber, createOrderReq.getIdNumber()).list();
        if (NullUtils.isNotEmpty(customers)) {
            customers.stream().filter(dbCus -> {
                return !StringUtils.isAnyEmpty(dbCus.getIdCardFront(), dbCus.getIdCardBack());
            }).findFirst().ifPresent(findCus -> {
                customer.setIdCardFront(findCus.getIdCardFront());
                customer.setIdCardBack(findCus.getIdCardBack());
            });
        }

        orderBase.setCustomerId(customer.getCustomerId());

        //加锁，防止重复创建
        RLock lock = redissonClient.getLock(Constants.ORDER_LOCK + createOrderReq.getIdNumber());
        boolean tryLock = false;
        try {
            tryLock = lock.tryLock(2, 5, TimeUnit.SECONDS);
            if (tryLock) {
                log.info("创建订单 {} 客户身份证 {}", orderBase.getOrderId(), customer.getIdNumber());
                orderService.save(orderBase);
                customerService.saveOrUpdate(customer);
            } else {
                throw new BizException("客户 {} 请不要在5秒中内，重复创建订单", createOrderReq.getIdNumber());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
//            if(tryLock){
//                lock.unlock();
//            }
        }

        optLog.saveOrderOperateLog(orderBase.getOrderId(), BizStageEnum.PRE_APPROVAL.getStageId(), null, null, DBConstants.OPT_NEW, orderBase);

        return orderBase;
    }


    /**
     * 提交预审信息
     * 预审也包含创建订单的流程
     * 预审喜喜主要包含部分： 客户信息、订单信息
     */
    public String putOrderPreApproval(PreApprovalDto preApprovalDto) {
        OrderBase orderBase;
        String orderId = preApprovalDto.getOrderId();
        if (NullUtils.isEmpty(orderId)) {
            CreateOrderReq createOrderReq = new CreateOrderReq();
            BeanUtil.copyProperties(preApprovalDto, createOrderReq, CopyOptions.create().setIgnoreNullValue(true));
            createOrderReq.setType(DBConstants.BIZ_TYPE_ZZD);
            orderBase = SpringUtil.getBean(BtoOrderService.class).createNewOrder(createOrderReq);
        } else {
            orderBase = orderService.getById(orderId);
        }

        Customer customer = customerService.getById(orderBase.getCustomerId());
        if (NullUtils.isAnyNull(orderBase, customer)) {
            throw new BizException("订单 {} 信息不存在/订单客户信息不存在", orderId);
        }
        BeanUtil.copyProperties(preApprovalDto, customer, CopyOptions.create().setIgnoreNullValue(true));
        BeanUtil.copyProperties(preApprovalDto, orderBase, CopyOptions.create().setIgnoreNullValue(true));

        customerService.updateById(customer);
        orderService.updateById(orderBase);

        val handler = stageHandlerFactory.getLeaseStageHandlerByStatusId(BizStageEnum.PRE_APPROVAL.getStageId());
        handler.createNewInitState(orderBase.getOrderId(), BizStageEnum.PRE_APPROVAL.getStageId(), BizTaskEnum.TASK_YSXX.getTaskId());

        optLog.saveOrderOperateLog(orderBase.getOrderId(), BizStageEnum.PRE_APPROVAL.getStageId(), BizTaskEnum.TASK_YSXX.getTaskId(),
                BizTaskStateEnum.WAITING_FILLED.getStateId(), DBConstants.OPT_UPDATE, preApprovalDto);

        return orderBase.getOrderId();
    }

    /**
     * 查询预审信息及状态
     */
    public PreApprovalDto getOrderPreApproval(String orderId) {
        PreApprovalDto preApprovalDto = new PreApprovalDto();
        OrderBase orderBase = orderService.getById(orderId);

        Customer customer = customerService.getById(orderBase.getCustomerId());
        BeanUtil.copyProperties(customer, preApprovalDto, CopyOptions.create().setIgnoreNullValue(true));
        BeanUtil.copyProperties(orderBase, preApprovalDto, CopyOptions.create().setIgnoreNullValue(true));
        if (NullUtils.isNull(orderBase.getIsSurety())) {
            preApprovalDto.setIsSurety(Byte.valueOf("0"));
        }
        preApprovalDto.setOrderState(btoOrderStateService.getOrderTaskState(orderId, BizStageEnum.PRE_APPROVAL.getStageId(), BizTaskEnum.TASK_YSXX.getTaskId()));
        preApprovalDto.setBtns(getFormBtns(orderId, BizStageEnum.PRE_APPROVAL.getStageId(), BizTaskEnum.TASK_YSXX.getTaskId()
                , ""));
        return preApprovalDto;
    }


    /**
     * 提交-业主信息
     */
    @Transactional
    public void putCustomerInfo(CustomerInfoDto customerInfoDto) {
        OrderBase orderBase = orderService.getById(customerInfoDto.getOrderId());
        Customer customer = customerService.getById(orderBase.getCustomerId());
        BeanUtil.copyProperties(customerInfoDto, customer, CopyOptions.create().setIgnoreNullValue(true));
        customerService.updateById(customer);

        BeanUtil.copyProperties(customerInfoDto, orderBase, CopyOptions.create().setIgnoreNullValue(true));
        orderService.updateById(orderBase);

//        if (StringUtils.isNotEmpty(customerInfoDto.getName())) {
//            //更新全部客户关联订单的姓名
//            orderService.lambdaUpdate()
//                    .eq(OrderBase::getCustomerId, customer.getCustomerId())
//                    .set(OrderBase::getName, customer.getName())
//                    .update();
//        }


        optLog.saveOrderOperateLog(orderBase.getOrderId(), BizStageEnum.CUSTOMER_INFO.getStageId(), null,
                BizTaskStateEnum.WAITING_FILLED.getStateId(), DBConstants.OPT_UPDATE, customerInfoDto);
    }

    /**
     * 查询-业主信息
     */
    public CustomerInfoDto getCustomerInfo(String orderId) {
        CustomerInfoDto customerInfoDto = new CustomerInfoDto();
        OrderBase orderBase = orderService.getById(orderId);
        Customer customer = customerService.getById(orderBase.getCustomerId());
        BeanUtils.copyPropertiesIgnoreNullValue(customer, customerInfoDto);
        BeanUtils.copyPropertiesIgnoreNullValue(orderBase, customerInfoDto);


        customerInfoDto.setOrderState(btoOrderStateService.getOrderTaskState(orderId, BizStageEnum.CUSTOMER_INFO.getStageId(), null));
        customerInfoDto.setBtns(getFormBtns(orderId, BizStageEnum.CUSTOMER_INFO.getStageId(), null, EditAndApprovalEnum.CUSTOMER_INFO_AUTH));
        return customerInfoDto;
    }

    /**---------------------------------踏勘信息-------------------------------**/
    /**
     * 提交踏勘信息
     */
    @Transactional
    public void putOrderTaKan(TaKanDto taKanDto) {
        //经纬度，在踏勘中确定
        orderService.lambdaUpdate()
                .set(OrderBase::getLng, taKanDto.getLng())
                .set(OrderBase::getLat, taKanDto.getLat())
                .eq(OrderBase::getOrderId, taKanDto.getOrderId()).update();

        Reconnoitre reconnoitre = new Reconnoitre();
        reconnoitre.setOrderId(taKanDto.getOrderId());
        BeanUtil.copyProperties(taKanDto, reconnoitre);

        Reconnoitre reconnoitreByDb = reconnoitreService.getById(reconnoitre.getOrderId());
        if (NullUtils.isNotNull(reconnoitreByDb)) {
            //去除业务踏勘的字段
            Set<String> updateSqlSet = WrappersFactory.setIgnoreList(TaKanDto.class);
            reconnoitreService.update(WrappersFactory.updateWithNullField(reconnoitre, updateSqlSet)
                    .eq(Reconnoitre::getOrderId, reconnoitre.getOrderId()));
        } else {
            reconnoitreService.save(reconnoitre);
        }

        optLog.saveOrderOperateLog(taKanDto.getOrderId(), BizStageEnum.KAN_CHA.getStageId(), BizTaskEnum.TASK_TA_KAN.getTaskId(),
                BizTaskStateEnum.WAITING_FILLED.getStateId(), DBConstants.OPT_UPDATE, taKanDto);
    }

    /**
     * 查询踏勘信息
     */
    public TaKanDto getOrderTaKan(String orderId) {
        TaKanDto taKanDto = new TaKanDto();
        OrderBase orderBase = orderService.getById(orderId);
        Reconnoitre reconnoitre = reconnoitreService.getById(orderId);
        BeanUtils.copyPropertiesConvertJson(reconnoitre, taKanDto);
        taKanDto.setLat(orderBase.getLat());
        taKanDto.setLng(orderBase.getLng());
        OrderState taskState = btoOrderStateService.getOrderTaskState(orderId, BizStageEnum.KAN_CHA.getStageId(),
                BizTaskEnum.TASK_TA_KAN.getTaskId());
        taKanDto.setOrderState(taskState);
        EditAndApprovalEnum editAndApprovalEnum;
        if (BizTaskStateEnum.WAITING_APPROVAL_INNER.getStateId().equals(taskState.getStateId())) {
            editAndApprovalEnum = EditAndApprovalEnum.TASK_TA_KAN_INNER_AUTH;
        } else {
            editAndApprovalEnum = EditAndApprovalEnum.TASK_TA_KAN_BTO_AUTH;
        }
        taKanDto.setBtns(getFormBtns(orderId, BizStageEnum.KAN_CHA.getStageId(), BizTaskEnum.TASK_TA_KAN.getTaskId(),
                editAndApprovalEnum));

        return taKanDto;
    }

    /**---------------------------------技术勘察信息-------------------------------**/
    /**
     * 提交-技术勘察信息
     */
    public void putOrderTecKanCha(TecKanChaDto tecKanChaDto) {
        Reconnoitre reconnoitre = new Reconnoitre();
        reconnoitre.setOrderId(tecKanChaDto.getOrderId());
        //BeanUtils.copyPropertiesIgnoreNullValue(tecKanChaDto, reconnoitre);
        BeanUtil.copyProperties(tecKanChaDto, reconnoitre);

        //计算拟安装容量 -- 前端传参数如果为kw 或者 浮点数 后端会掉失精度
        Integer modulePower = tecKanChaDto.getModulePower();
        Integer modulerNumberReckon = tecKanChaDto.getModuleNumberReckon();
        if (NullUtils.isNotNull(modulePower) && NullUtils.isNotNull(modulerNumberReckon)) {
            Integer installedCapacityReckon = modulePower * modulerNumberReckon;
            reconnoitre.setInstalledCapacityReckon(installedCapacityReckon);
        }


        Reconnoitre reconnoitreByDb = reconnoitreService.getById(tecKanChaDto.getOrderId());
        if (NullUtils.isNotNull(reconnoitreByDb)) {
            //去除业务踏勘的字段
            Set<String> removeListSet = WrappersFactory.setIgnoreList(TaKanDto.class);
            Set<String> updateSqlSet = WrappersFactory.setIgnoreList(TecKanChaDto.class, removeListSet);
            reconnoitreService.update(WrappersFactory.updateWithNullField(reconnoitre, updateSqlSet)
                    .eq(Reconnoitre::getOrderId, tecKanChaDto.getOrderId()));
        } else {
            reconnoitreService.save(reconnoitre);
        }

        optLog.saveOrderOperateLog(tecKanChaDto.getOrderId(), BizStageEnum.KAN_CHA.getStageId(), BizTaskEnum.TASK_JSKC.getTaskId(),
                BizTaskStateEnum.WAITING_FILLED.getStateId(), DBConstants.OPT_UPDATE, tecKanChaDto);
    }

    /**
     * 查询-技术勘察信息
     */
    public TecKanChaDto getOrderTecKanCha(String orderId) {
        TecKanChaDto tecKanChaDto = new TecKanChaDto();
        Reconnoitre reconnoitre = reconnoitreService.getById(orderId);
        tecKanChaDto.setOrderId(reconnoitre.getOrderId());
        tecKanChaDto.setOrderBase(orderService.getById(orderId));
        BeanUtil.copyProperties(reconnoitre, tecKanChaDto, CopyOptions.create().setIgnoreNullValue(true));

        Appoint appoint = appointService.lambdaQuery().eq(Appoint::getOrderId, orderId)
                .select(Appoint::getUserId)
                .eq(Appoint::getOrderId, orderId)
                .eq(Appoint::getStageId, BizStageEnum.KAN_CHA.getStageId())
                .eq(Appoint::getTaskId, BizTaskEnum.TASK_JSKC.getTaskId())
                .eq(Appoint::getStateId, BizTaskStateEnum.WAITING_APPOINT.getStateId()).one();
        if (NullUtils.isNotNull(appoint)) {
            tecKanChaDto.setAppointUser(btoUserService.getUserByUserId(appoint.getUserId()));
        }
        tecKanChaDto.setOrderState(btoOrderStateService.getOrderTaskState(orderId, BizStageEnum.KAN_CHA.getStageId(),
                BizTaskEnum.TASK_JSKC.getTaskId()));

        tecKanChaDto.setBtns(getFormBtns(orderId, BizStageEnum.KAN_CHA.getStageId(),
                BizTaskEnum.TASK_JSKC.getTaskId(), EditAndApprovalEnum.TASK_JSKC_BTO_AUTH));

        return tecKanChaDto;
    }

    /**
     * ---------------------------------签约合同-------------------------------
     **/
    public LeaseContractDto getOrderLeaseContractSign(String orderId) {
        //TODO  通过越秀合同接口查询合同
        LeaseContractDto leaseContractDto = new LeaseContractDto();
        //同步越秀状态
        leaseApi.updateLeaseStateToBtoState(orderId);
        leaseContractDto.setOrderId(orderId);
        leaseContractDto.setLeaseSigneUrl(btoLeaseReviewService.getSignUrlByOrderId(orderId));
        OrderState orderTaskState = btoOrderStateService.getOrderTaskState(orderId, BizStageEnum.LEASE_SIGN.getStageId(), BizTaskEnum.TASK_HTQY.getTaskId(), false);
        if (NullUtils.isNotNull(orderTaskState)) {
            leaseContractDto.setState(orderTaskState.getStateId());
        }
        leaseContractDto.setOrderState(orderTaskState);
        return leaseContractDto;
    }


    /**
     * ---------------------------------设计信息-------------------------------
     **/
    @Transactional
    public void putOrderDesign(DesignDto design) {
        design.setInstalledCapacityDesign(null);
        design.setModulePower(null);
        design.setModuleNumberDesign(null);
        DesignStageHandler designStageHandler = (DesignStageHandler) stageHandlerFactory.getLeaseStageHandlerByStatusId(BizStageEnum.DESIGN.getStageId());

        List<DesignDto.DesignDevice> designDevices = design.getDesignDevice();

        if (NullUtils.isNotEmpty(designDevices)) {
            designDevices.forEach(designDevice -> {
                if (Constants.DEVICE_TYPE_ZUJIAN.equals(designDevice.getDeviceType())) {
                    if (StringUtils.isNotEmpty(designDevice.getDeviceSpec()) && NullUtils.isNotNull(designDevice.getQuantity())) {
                        design.setModulePower(Integer.valueOf(designDevice.getDeviceSpec()));
                        design.setModuleNumberDesign(designDevice.getQuantity());
                        design.setInstalledCapacityDesign(design.getModuleNumberDesign() * design.getModulePower());
                    }
                }
            });
        }


        boolean newDesignUpdate = designStageHandler.canCreateNewDesignUpdate(design.getOrderId());
        String taskId = BizTaskEnum.TASK_CSPSXX.getTaskId();

        List<Design> designList = designService.lambdaQuery().eq(Design::getOrderId, design.getOrderId()).orderByDesc(Design::getCreateTime).list();
        if (NullUtils.isEmpty(designList)) {
            //保存新的设计变更信息
            design.setId(IdUtils.fastUUID());
            designService.save(design);
        } else {
            design.setId(designList.get(0).getId());
            Design designByNew = new Design();
            BeanUtil.copyProperties(design, designByNew);
            List<String> removeList = Collections.singletonList("state");
            Set<String> removeSet = new HashSet<>(removeList);
            if (designList.size() == 1) {
                //如果记录并且有一个就是初设评审
                Set<String> updateSqlSet = WrappersFactory.setIgnoreList(Design.class, removeSet);
                designService.update(WrappersFactory.updateWithNullField(designByNew, updateSqlSet)
                        .eq(Design::getId, designByNew.getId()));
            } else {
                if (!BizTaskStateEnum.APPROVAL_PASS_BTO.getStateId().equals(designList.get(0).getState())) {
                    taskId = BizTaskEnum.TASK_CSPSXX_UPDATE.getTaskId();
                    newDesignUpdate = false;
                    Set<String> updateSqlSet = WrappersFactory.setIgnoreList(Design.class, removeSet);
                    designService.update(WrappersFactory.updateWithNullField(designByNew, updateSqlSet)
                            .eq(Design::getId, designByNew.getId()));
                }
            }
        }

        //创建新的设计变更
        if (newDesignUpdate) {
            //保存新的设计变更信息
            design.setId(IdUtils.fastUUID());
            //创建新的设计变更状态
            designStageHandler.createDesignUpdateState(design.getOrderId());
            taskId = BizTaskEnum.TASK_CSPSXX_UPDATE.getTaskId();
            designService.save(design);
        }

        optLog.saveOrderOperateLog(design.getOrderId(), BizStageEnum.DESIGN.getStageId(), taskId,
                BizTaskStateEnum.WAITING_FILLED.getStateId(), DBConstants.OPT_UPDATE, design);
    }

    public DesignDto getOrderDesign(String orderId, Integer times) {
        DesignDto designDto = new DesignDto();
        String taskId = BizTaskEnum.TASK_CSPSXX.getTaskId();
        Design design;
        if (0 == times) {
            design = btoDesignService.getFirestDesign(orderId);
        } else {
            taskId = BizTaskEnum.TASK_CSPSXX_UPDATE.getTaskId();
            design = btoDesignService.getLatestDesign(orderId, false);
        }
        BeanUtils.copyPropertiesConvertJson(design, designDto);

        OrderLogReq orderLogReq = new OrderLogReq();
        orderLogReq.setOrderId(orderId);
        designDto.setOrderState(btoOrderStateService.getOrderTaskState(orderId, BizStageEnum.DESIGN.getStageId(),
                taskId));

        designDto.setBtns(getFormBtns(orderId, BizStageEnum.DESIGN.getStageId(),
                taskId, EditAndApprovalEnum.TASK_CSPSXX_BTO_AUTH));
        return designDto;
    }
    /**---------------------------------施工信息-------------------------------**/
    /**
     * 提交-施工信息
     */
    public void putOrderConstruct(Construct construct) {
        //获取设计容量信息
        Design design = btoDesignService.getLatestDesign(construct.getOrderId(), true);
        if (NullUtils.isNull(design)) {
            throw new BizException("订单{} 施工没有找到设计信息", construct.getOrderId());
        }
        construct.setInstalledCapacityReality(design.getInstalledCapacityDesign());
        construct.setModuleNumberReality(design.getModuleNumberDesign());

        Construct constructByDb = constructService.getById(construct.getOrderId());
        if (NullUtils.isNotNull(constructByDb)) {
            Set<String> updateSqlSet = WrappersFactory.setIgnoreList(ConstructSGXXDto.class);
            constructService.update(WrappersFactory.updateWithNullField(construct, updateSqlSet)
                    .eq(Construct::getOrderId, construct.getOrderId()));
        } else {
            constructService.save(construct);
        }
        constructService.saveOrUpdate(construct);
        optLog.saveOrderOperateLog(construct.getOrderId(), BizStageEnum.CONSTRUCT.getStageId(), BizTaskEnum.TASK_SGXX.getTaskId(),
                BizTaskStateEnum.WAITING_FILLED.getStateId(), DBConstants.OPT_UPDATE, construct);
    }

    /**
     * 查询-施工信息
     */
    public ConstructDto getOrderConstruct(String orderId) {
        ConstructDto constructDto = new ConstructDto();
        Design design = btoDesignService.getLatestDesign(orderId, true);
        if (NullUtils.isNull(design)) {
            throw new BizException("订单 {} 未找到设计阶段，设计信息", orderId);
        }
        constructDto.setModulePower(design.getModulePower());
        constructDto.setModuleNumberReality(design.getModuleNumberDesign());
        constructDto.setInstalledCapacityReality(design.getInstalledCapacityDesign());

        Construct construct = constructService.getById(orderId);
        BeanUtil.copyProperties(construct, constructDto, CopyOptions.create().setIgnoreNullValue(true));

        //除了供应商DLS类型的公司用自己的公司名称，其他类型都使用总部公司名称
        OrderBase orderBase = orderService.getById(orderId);
        if (NullUtils.isNull(orderBase)) {
            throw new BizException("订单{} 未找到", orderId);
        }
        Company company = companyService.getById(orderBase.getCompanyId());
        if (NullUtils.isNull(company)) {
            throw new BizException("订单{} 施工单位未找到", orderId);
        }
        if (DBConstants.COMPANY_TYPE_AGENT.equals(company.getType())) {
            constructDto.setOrganization(company.getName());
        } else {
            constructDto.setOrganization(DBConstants.COMPANY_ZBGS_NAME);
        }


        constructDto.setOrderState(btoOrderStateService.getOrderTaskState(orderId, BizStageEnum.CONSTRUCT.getStageId(),
                BizTaskEnum.TASK_SGXX.getTaskId()));
        constructDto.setBtns(getFormBtns(orderId, BizStageEnum.CONSTRUCT.getStageId(),
                BizTaskEnum.TASK_SGXX.getTaskId(), EditAndApprovalEnum.TASK_SGXX_BTO_AUTH));
        return constructDto;
    }

    /**---------------------------------施工-影像件信息-------------------------------**/
    /**
     * 提交-施工照片信息
     */
    public void putOrderConstructImages(ConstructDto constructDto) {
        Construct construct = constructService.getById(constructDto.getOrderId());
        BeanUtils.copyPropertiesConvertJson(constructDto, construct);
        if (NullUtils.isNull(construct)) {
            constructService.save(construct);
        } else {
            Set<String> removeSet = WrappersFactory.setIgnoreList(ConstructSGXXDto.class);
            Set<String> updateSqlSet = WrappersFactory.setIgnoreList(Construct.class, removeSet);
            constructService.update(WrappersFactory.updateWithNullField(construct, updateSqlSet)
                    .eq(Construct::getOrderId, constructDto.getOrderId()));
        }
        optLog.saveOrderOperateLog(construct.getOrderId(), BizStageEnum.CONSTRUCT.getStageId(), BizTaskEnum.TASK_SGYXJXX.getTaskId(),
                BizTaskStateEnum.WAITING_FILLED.getStateId(), DBConstants.OPT_UPDATE, construct);
    }

    /**
     * 查询-施工照片信息
     */
    public ConstructDto getOrderConstructImages(String orderId) {
        ConstructDto constructDto = new ConstructDto();
        Construct construct = constructService.getById(orderId);
        BeanUtils.copyPropertiesConvertJson(construct, constructDto);
        constructDto.setOrderState(btoOrderStateService.getOrderTaskState(orderId, BizStageEnum.CONSTRUCT.getStageId(),
                BizTaskEnum.TASK_SGYXJXX.getTaskId()));
        constructDto.setBtns(getFormBtns(orderId, BizStageEnum.CONSTRUCT.getStageId(),
                BizTaskEnum.TASK_SGYXJXX.getTaskId(), EditAndApprovalEnum.TASK_SGXX_BTO_AUTH));
        return constructDto;
    }


    /**---------------------------------施工-设备信息-------------------------------**/
    /**
     * 提交施工设备基础信息
     * 流程更新：设计阶段只规定规格，设备表只保存设备码，厂家信息通过sto查询（规格一样，厂家不同情形）
     * 规格一样的设备归一处理
     */
    @Transactional
    public void putOrderConstructDevice(DeviceDto deviceDto) {
        Design design = btoDesignService.getLatestDesign(deviceDto.getOrderId(), true);
        if (design == null) {
            throw new BizException("未找到对应订单{}的设计信息", deviceDto.getOrderId());
        }
        List<DesignDto.DesignDevice> designDevice = design.getDesignDevice();
        if (NullUtils.isEmpty(designDevice)) {
            throw new BizException("设计信息未找到，订单{}", deviceDto.getOrderId());
        }


        List<Device> updateDevices = deviceDto.getDevices();
        //删除旧的
        deviceService.remove(Wrappers.<Device>lambdaQuery()
                .eq(Device::getOrderId, deviceDto.getOrderId())
                .eq(Device::getDeviceType, deviceDto.getDeviceType()));
        if (NullUtils.isEmpty(updateDevices)) {
            return;
        }

        //校验提交设备编码合理性
//        checkDeviceValidRes = btoDeviceService.checkUploadDeviceCodeIsValid(updateDevices);
//        updateDevices = checkDeviceValidRes.getValidDevices();

//        String orderId = updateDevices.get(0).getOrderId();
//        String deviceType = updateDevices.get(0).getDeviceType();

        for (Device device : updateDevices) {
            device.setId(IdUtils.fastSnowId());
            for (DesignDto.DesignDevice designDeviceDb : designDevice) {
                if (designDeviceDb.getDeviceType().equals(device.getDeviceType()) && Constants.DEVICE_TYPE_ZUJIAN.equals(designDeviceDb.getDeviceType())) {
                    int deviceSpec = Integer.parseInt(designDeviceDb.getDeviceSpec());
                    device.setModulePower(deviceSpec);
                }
            }
        }

        deviceService.saveBatch(updateDevices);

        Device device = updateDevices.get(0);
        optLog.saveOrderOperateLog(device.getOrderId(), BizStageEnum.CONSTRUCT.getStageId(), "TASK_SBXX_" + device.getDeviceType(),
                BizTaskStateEnum.WAITING_FILLED.getStateId(), DBConstants.OPT_UPDATE, deviceDto);
    }

    /**
     * 提交施工设备扫码编号
     * 需要记录每一个设备扫码的时间
     */
    public void putOrderConstructDeviceScan(DeviceDto deviceDto) {
    }

    public DeviceDto getOrderConstructDevice(String orderId, String deviceType) {
        DeviceDto deviceDto = new DeviceDto();
        OrderBase orderBase = orderService.getById(orderId);
        //返回项目定位
        deviceDto.setLng(String.valueOf(orderBase.getLng()));
        deviceDto.setLat(String.valueOf(orderBase.getLat()));
        List<Device> deviceList = deviceService.lambdaQuery().eq(Device::getOrderId, orderId)
                .eq(Device::getDeviceType, deviceType).list();


        List<DesignDto.DesignDevice> designDevice = btoDesignService.getOrderDesignDeviceSpecInfo(orderId, deviceType);
        deviceDto.setDesignDevice(designDevice);
        CheckDeviceValidRes checkDeviceValidRes = new CheckDeviceValidRes();
        if (Constants.NEED_VALID_CODE_DEV.contains(deviceType)) {
            checkDeviceValidRes = btoDeviceService.checkUploadDeviceCodeIsValid(deviceList);
        }
        //非校验的设备直接通过
        else {
            List<DeviceVo> validDevices = new ArrayList<>();
            deviceList.forEach(device -> {
                DeviceVo deviceVo = new DeviceVo();
                BeanUtils.copyPropertiesIgnoreNullValue(device, deviceVo);
                validDevices.add(deviceVo);
            });
            checkDeviceValidRes.setDeviceVos(validDevices);
        }
        deviceDto.setCheckDeviceValidRes(checkDeviceValidRes);

        String taskId = null;
        if (StringUtils.isNotEmpty(deviceType)) {
            taskId = "TASK_SBXX_" + deviceType;
        }
        deviceDto.setOrderState(btoOrderStateService.getOrderTaskState(orderId, BizStageEnum.CONSTRUCT.getStageId(), taskId));
        deviceDto.setBtns(getFormBtns(orderId, BizStageEnum.CONSTRUCT.getStageId(),
                taskId, EditAndApprovalEnum.TASK_SGXX_BTO_AUTH));
        return deviceDto;
    }


    /**
     * ---------------------------------备案证信息-------------------------------
     **/
    public void putOrderRecord(RecordDto recordDto) {
        Record record = recordService.getById(recordDto.getRecordCertificateId());
        User curUser = btoUserService.getCurrentUser();

        //先获取OrderBase，检查订单中是否存在备案证编码，如果没有就直接更新，不需要归回剩余容量
        OrderBase orderBase = orderService.getById(recordDto.getOrderId());
        if (NullUtils.isNull(orderBase)) {
            throw new BizException("没有找到该订单 {} 信息,无法更新备案证信息", recordDto.getOrderId());
        }
        //更新备案证信息
        customerService.lambdaUpdate().set(Customer::getPropertyCertificate , recordDto.getPropertyCertificate())
                .eq(Customer::getCustomerId , orderBase.getCustomerId()).update();


        //新增备案证
        if (StringUtils.isNotEmpty(recordDto.getRecordCertificateId()) && NullUtils.isNull(record)) {
            if (StringUtils.isNotEmpty(recordDto.getRecordCertificateId())) {
                record = new Record();
                BeanUtils.copyPropertiesIgnoreNullValue(recordDto, record);
                if (1 == recordDto.getRecordType()) {
                    record.setSurplusCapacity(recordDto.getRecordCertificateCapacity());
                }
                List<Long> accreditCompanyIds = new ArrayList<>();
                accreditCompanyIds.add(orderBase.getCompanyId());
                JSONArray jsonArray = new JSONArray(accreditCompanyIds);
                record.setAccreditCompanyIds(jsonArray.toJSONString());
                record.setUserId(curUser.getUserId());
                recordService.save(record);
            }
        } else {
            //备案证类型不能修改
            if (NullUtils.isNotNull(recordDto.getRecordType())) {
                if (!record.getRecordType().equals(recordDto.getRecordType())) {
                    throw new BizException("该备案证编码{}，无法{}从转成{}",
                            record.getRecordCertificateId(), record.getRecordType(),
                            recordDto.getRecordType());
                }
            }
        }


        //校验是否授权该订单的所属公司
        if (NullUtils.isNotNull(record) && StringUtils.isNotEmpty(record.getAccreditCompanyIds())) {
            List<Long> companyIds = JSONArray.parseArray(record.getAccreditCompanyIds(), Long.class);
            if (NullUtils.isNotEmpty(companyIds)) {
                if (!companyIds.contains(orderBase.getCompanyId())) {
                    throw new BizException("订单{}的该备案证编码{}，没有授权所属组织，无法使用",
                            recordDto.getOrderId(), record.getRecordCertificateId());
                }
            }
        }

        if (StringUtils.isNotEmpty(orderBase.getRecordCertificateId())) {
            btoRecordService.updateRecordSurplusCapacity(record, orderBase);
        }
        //更新订单的备案证信息
        orderService.lambdaUpdate().eq(OrderBase::getOrderId, recordDto.getOrderId())
                .set(OrderBase::getRecordCertificateId, recordDto.getRecordCertificateId()).update();

        optLog.saveOrderOperateLog(recordDto.getOrderId(), BizStageEnum.BAZING.getStageId(), BizTaskEnum.TASK_BAZXX.getTaskId(),
                BizTaskStateEnum.WAITING_FILLED.getStateId(), DBConstants.OPT_UPDATE, recordDto);
    }

    public RecordDto getOrderRecord(String orderId) {
        OrderBase orderBase = orderService.getById(orderId);
        Record record = recordService.getById(orderBase.getRecordCertificateId());
        Reconnoitre reconnoitre = reconnoitreService.getById(orderId);
        RecordDto recordDto = new RecordDto();
        //返回前端，订单的踏勘拟安装容量
        recordDto.setInstalledCapacityReckon(reconnoitre.getInstalledCapacityReckon());
        Customer customer = customerService.getById(orderBase.getCustomerId());
        recordDto.setPropertyCertificate(customer.getPropertyCertificate());

        if (NullUtils.isNotNull(record)) {
            BeanUtils.copyPropertiesIgnoreNullValue(record, recordDto);
            LeaseLessor leaseLessor = leaseLessorService.lambdaQuery().eq(LeaseLessor::getCode, record.getCompanyId()).one();
            recordDto.setLeaseCompanyName(leaseLessor.getCompanyName());
        }

        recordDto.setOrderId(orderId);
        recordDto.setOrderState(btoOrderStateService.getOrderTaskState(orderId, BizStageEnum.BAZING.getStageId(), BizTaskEnum.TASK_BAZXX.getTaskId()));
        recordDto.setBtns(getFormBtns(orderId, BizStageEnum.BAZING.getStageId(),
                BizTaskEnum.TASK_BAZXX.getTaskId(), EditAndApprovalEnum.TASK_BAZXX_BTO_AUTH));
        return recordDto;
    }

    /** ---------------------------------并网信息-------------------------------**/
    /**
     * 提交并网信息
     */
    public void putOrderGrid(OrderGridDto gridDto) {
        GridConnection gridConnection = new GridConnection();
        BeanUtils.copyPropertiesIgnoreNullValue(gridDto, gridConnection);

        GridConnection gridConnectionByDb = gridConnectionService.getById(gridDto.getOrderId());
        if (NullUtils.isNotNull(gridConnectionByDb)) {
            Set<String> updateSqlSet = WrappersFactory.setIgnoreList(OrderGridDto.class);
            gridConnectionService.update(WrappersFactory.updateWithNullField(gridConnection, updateSqlSet)
                    .eq(GridConnection::getOrderId, gridDto.getOrderId()));
        } else {
            gridConnectionService.save(gridConnection);
        }

        gridDto.setInsuranceList(gridDto.getInsuranceList().stream().filter(insurance -> {
            return StringUtils.isNotEmpty(insurance.getInsuranceNumber());
        }).collect(Collectors.toList()));

        insuranceService.saveOrUpdateBatch(gridDto.getInsuranceList());

        optLog.saveOrderOperateLog(gridDto.getOrderId(), BizStageEnum.GRID_CONNECTION.getStageId(), BizTaskEnum.TASK_BWXX.getTaskId(),
                BizTaskStateEnum.WAITING_FILLED.getStateId(), DBConstants.OPT_UPDATE, gridDto);

    }

    public OrderGridDto getOrderGrid(String orderId) {
        val gridConnection = gridConnectionService.getById(orderId);
        val insuranceList = insuranceService.lambdaQuery().eq(Insurance::getOrderId, orderId)
//                .eq(Insurance::getInsureType, 1)
                .list();

        Construct construct = constructService.getById(orderId);

        OrderGridDto orderGridDto = new OrderGridDto();
        //施工安装容量
        if (NullUtils.isNull(construct)) {
            log.error("并网未查到施工信息 订单{}", orderId);
        } else {
            orderGridDto.setInstalledCapacityReality(construct.getInstalledCapacityReality());
        }

        BeanUtils.copyPropertiesConvertJson(gridConnection, orderGridDto);
        orderGridDto.setInsuranceList(insuranceList);


        orderGridDto.setOrderState(btoOrderStateService.getOrderTaskState(orderId, BizStageEnum.GRID_CONNECTION.getStageId(), BizTaskEnum.TASK_BWXX.getTaskId()));
        orderGridDto.setBtns(getFormBtns(orderId, BizStageEnum.GRID_CONNECTION.getStageId(),
                BizTaskEnum.TASK_BWXX.getTaskId(), EditAndApprovalEnum.TASK_BWXX_BTO_AUTH));
        return orderGridDto;
    }

    /** ---------------------------------结算信息-------------------------------**/
    /**
     * 提交并网结算信息(直营 、 代理商：并网结算、资料结算)
     */
    public void putOrderGridSettlement(Settlement settlement) {
        Settlement one = settlementService.lambdaQuery()
                .eq(Settlement::getOrderId, settlement.getOrderId())
                .eq(Settlement::getSettlementType, settlement.getSettlementType())
                .one();
        if (NullUtils.isNull(one)) {
            settlement.setId(IdUtils.fastSnowId());
            settlementService.save(settlement);
        } else {
            settlement.setId(one.getId());
            Set<String> updateSqlSet = WrappersFactory.setIgnoreList(Settlement.class);
            settlementService.update(WrappersFactory.updateWithNullField(settlement, updateSqlSet)
                    .eq(Settlement::getId, settlement.getId()));
        }

        String taskId = null;
        if (DBConstants.SETTL_BW.equals(settlement.getSettlementType())) {
            taskId = BizTaskEnum.TASK_BWJSXX.getTaskId();
        } else if (DBConstants.SETTL_ZL.equals(settlement.getSettlementType())) {
            taskId = BizTaskEnum.TASK_ZLJSXX.getTaskId();
        }


        optLog.saveOrderOperateLog(settlement.getOrderId(), BizStageEnum.SETTLEMENT.getStageId(), taskId,
                BizTaskStateEnum.WAITING_FILLED.getStateId(), DBConstants.OPT_UPDATE, settlement);
    }

    public SettlementDto getOrderGridSettlement(Settlement query) {
        SettlementDto settlementDto = new SettlementDto();
        val settlement = settlementService.lambdaQuery()
                .eq(Settlement::getOrderId, query.getOrderId())
                .eq(Settlement::getSettlementType, query.getSettlementType()).one();
        BeanUtil.copyProperties(settlement, settlementDto, CopyOptions.create().setIgnoreNullValue(true));
        if (DBConstants.SETTL_ZF.equals(query.getSettlementType())) {
            settlementDto.setOrderState(btoOrderStateService.getOrderTaskState(query.getOrderId(), BizStageEnum.SETTLEMENT.getStageId(), null));
            settlementDto.setBtns(getFormBtns(query.getOrderId(), BizStageEnum.SETTLEMENT.getStageId(),
                    null, EditAndApprovalEnum.TASK_JSXX_BTO_AUTH));
        } else if (DBConstants.SETTL_BW.equals(query.getSettlementType())) {
            settlementDto.setOrderState(btoOrderStateService.getOrderTaskState(query.getOrderId(), BizStageEnum.SETTLEMENT.getStageId(),
                    BizTaskEnum.TASK_BWJSXX.getTaskId()));
            settlementDto.setBtns(getFormBtns(query.getOrderId(), BizStageEnum.SETTLEMENT.getStageId(),
                    BizTaskEnum.TASK_BWJSXX.getTaskId(), EditAndApprovalEnum.TASK_JSXX_BTO_AUTH));
        } else if (DBConstants.SETTL_ZL.equals(query.getSettlementType())) {
            settlementDto.setOrderState(btoOrderStateService.getOrderTaskState(query.getOrderId(), BizStageEnum.SETTLEMENT.getStageId(),
                    BizTaskEnum.TASK_ZLJSXX.getTaskId()));
            settlementDto.setBtns(getFormBtns(query.getOrderId(), BizStageEnum.SETTLEMENT.getStageId(),
                    BizTaskEnum.TASK_ZLJSXX.getTaskId(), EditAndApprovalEnum.TASK_JSXX_BTO_AUTH));
        }
        return settlementDto;
    }


    /**
     * ---------------------------------购售电合同信息-------------------------------
     **/
    public void putOrderGSContract(GridConnection gridConnection) {
        gridConnectionService.updateById(gridConnection);
        optLog.saveOrderOperateLog(gridConnection.getOrderId(), BizStageEnum.GS_CONTRACT.getStageId(), BizTaskEnum.TASK_GSDHTXX.getTaskId(),
                BizTaskStateEnum.WAITING_FILLED.getStateId(), DBConstants.OPT_UPDATE, gridConnection);
    }

    public GSContractDto getOrderGSContract(String orderId) {
        GSContractDto gsContractDto = new GSContractDto();
        val gridConnection = gridConnectionService.getById(orderId);
        if (NullUtils.isNotNull(gridConnection)) {
            BeanUtils.copyPropertiesIgnoreNullValue(gridConnection, gsContractDto);
        }
        gsContractDto.setOrderState(btoOrderStateService.getOrderTaskState(orderId, BizStageEnum.GS_CONTRACT.getStageId(),
                BizTaskEnum.TASK_GSDHTXX.getTaskId()));
        gsContractDto.setBtns(getFormBtns(orderId, BizStageEnum.GS_CONTRACT.getStageId(),
                BizTaskEnum.TASK_GSDHTXX.getTaskId(), EditAndApprovalEnum.TASK_GSDHTXX_BTO_AUTH));

        return gsContractDto;
    }

    /**
     * 查询业主收益
     */
    public OperatingFarmGinsRes queryCustomerEarnings(QueryCusEarningsReq queryCusEarningsReq) {
        //越秀收益查询
        OrderBase orderBase = orderService.getById(queryCusEarningsReq.getOrderId());
        OperatingFarmGinsReqBody.OlDocumentFarmGainsDto req = new OperatingFarmGinsReqBody.OlDocumentFarmGainsDto();
        req.setPartnersContractNumber(queryCusEarningsReq.getOrderId());
        req.setSynchronizationType(queryCusEarningsReq.getType());
        req.setDueDateFrom(DateUtils.parseDateToStr("yyyyMMdd", queryCusEarningsReq.getStartTime()));
        req.setDueDateTo(DateUtils.parseDateToStr("yyyyMMdd", queryCusEarningsReq.getEndTime()));

        val res = leaseApi.operatingFarmFainsQuery(orderBase, req);
        if (NullUtils.isNotNull(res)) {
            return res;
        }
        throw new BizException("农户收益查询失败 {}", JSON.toJSONString(queryCusEarningsReq));
    }

    /**
     * 查询审批订单（待审批，已审批）
     */
    public PageInfo<QueryOrderRes> getOrderApprovalList(QueryOrderReq orderReq, Integer pageNum, Integer pageSize) {
        LambdaQueryWrapper<OrderState> lambdaQueryWrapper = btoOrderStateService.getOrderIdsByStates(orderReq.getStageId(), orderReq.getTaskId(),
//                Arrays.asList(BizStageEnum.FINISHED.getStageId()) ,
                Constants.WAITING_APPROVAL, Constants.PASS, Constants.REJECT);
        if (StringUtils.isEmpty(orderReq.getTaskId())) {
            lambdaQueryWrapper.isNull(OrderState::getTaskId);
        }
        lambdaQueryWrapper.orderByAsc(OrderState::getSort);
        PageHelper.startPage(pageNum, pageSize);
        List<OrderState> orderStates = orderStateService.list(lambdaQueryWrapper);
        PageInfo pageInfoTmp = new PageInfo(orderStates);
        List<QueryOrderRes> queryOrderResList = new ArrayList<>();
        orderStates.forEach(orderState -> {
            QueryOrderRes res = new QueryOrderRes();
            OrderBase orderBase = orderService.getById(orderState.getOrderId());
            if (NullUtils.isNotNull(orderBase)) {
                res.setOrderBase(orderService.getById(orderState.getOrderId()));
                res.setCompany(companyService.getById(res.getOrderBase().getCompanyId()));
                res.setCurrentOrderState(btoOrderStateService.getOrderCurrentStates(orderState.getOrderId()));
                queryOrderResList.add(res);
            }
        });
        PageInfo<QueryOrderRes> pageInfo = new PageInfo<>();
        BeanUtils.copyPropertiesIgnoreNullValue(pageInfoTmp, pageInfo);
        pageInfo.setList(queryOrderResList);
        return pageInfo;
    }


    /**
     * 订单列表查询
     */
    public PageInfo<QueryOrderRes> getOrderList(QueryOrderReq orderReq, Integer pageNum, Integer pageSize) {
//        removeUselessOrderStates();
        if (NullUtils.isNull(orderReq)) {
            orderReq = new QueryOrderReq();
        }
        val orderLambdaQueryWrapper = buildOrderQueryWrapper(orderReq);
        PageHelper.startPage(pageNum, pageSize);
        val orderList = orderService.list(orderLambdaQueryWrapper);
        val pageInfoTemp = new PageInfo<>(orderList);
        List<QueryOrderRes> queryOrderResList = new ArrayList<>();
        orderList.forEach(order -> {
            QueryOrderRes queryOrderRes = new QueryOrderRes();
            queryOrderRes.setOrderBase(orderService.getById(order.getOrderId()));
            Customer customer = customerService.getById(order.getCustomerId());
            if (NullUtils.isNull(customer)) {
                orderService.removeById(order.getOrderId());
            } else {
                queryOrderRes.setCustomer(customerService.getById(order.getCustomerId()));
                queryOrderRes.setCompany(companyService.getById(order.getCompanyId()));
                queryOrderRes.setLeaseReview(leaseReviewService.lambdaQuery().eq(LeaseReview::getOrderId, order.getOrderId()).one());
                queryOrderRes.setLeaseLessor(leaseLessorService.lambdaQuery().eq(LeaseLessor::getCode, order.getProjectCompany()).one());
                queryOrderRes.setLeasePrjProjectProduct(leasePrjProjectProductService.lambdaQuery().eq(LeasePrjProjectProduct::getCode, order.getProductWithArea()).one());
                queryOrderRes.setDesign(btoDesignService.getLatestDesign(order.getOrderId(), false));
                queryOrderRes.setCurrentOrderState(btoOrderStateService.getOrderCurrentStates(order.getOrderId()));
                queryOrderRes.setOrderStates(btoOrderStateService.getOrderStates(order.getOrderId()));
                queryOrderRes.setHasPutApprovalConstructBtn(btoUserService.isCurrentUserHasPermission(DBConstants.PER_CONSTRUCT));
                queryOrderResList.add(queryOrderRes);
            }
        });
        PageInfo<QueryOrderRes> pageInfo = new PageInfo<>();
        BeanUtils.copyPropertiesIgnoreNullValue(pageInfoTemp, pageInfo);
        pageInfo.setList(queryOrderResList);
        UserSearchRecord searchRecord = new UserSearchRecord();
        searchRecord.setUserId(btoUserService.getCurrentUser().getUserId());
        if (StringUtils.isNotEmpty(orderReq.getQueryTag())) {
            searchRecord.setSearchContent(JSON.toJSONString(orderReq));
            userSearchRecordService.save(searchRecord);
        }
        return pageInfo;
    }

    /**
     * 删除订单状态表，无用数的数据
     */
    private void removeUselessOrderStates() {
        List<String> collect = orderService.lambdaQuery()
                .select(OrderBase::getOrderId)
                .list().stream().map(OrderBase::getOrderId).collect(Collectors.toList());
        QueryWrapper<OrderState> queryWrapper = new QueryWrapper<>();
        queryWrapper.notIn(NullUtils.isNotEmpty(collect), "order_id", collect);
        orderStateService.remove(queryWrapper);
    }


    /**
     * 构建订单的查询条件 TODO 状态查询需要改为连接查询
     */
    public LambdaQueryWrapper<OrderBase> buildOrderQueryWrapper(QueryOrderReq orderReq) {

        LambdaQueryWrapper<OrderBase> queryWrapper = btoUserService.getCurrentUserOrderScopedLambdaQueryWrapper();
//        queryWrapper.select(OrderBase::getOrderId , OrderBase::getCustomerId , OrderBase::getCompanyId);
        LambdaQueryWrapper<Customer> cusQueryWrapper = new LambdaQueryWrapper<>();
        cusQueryWrapper.select(Customer::getCustomerId);
        LambdaQueryWrapper<OrderState> orderStateQueryWrapper = new LambdaQueryWrapper<>();
        orderStateQueryWrapper.select(OrderState::getOrderId);
        LambdaQueryWrapper<LeaseReview> leaseReviewLambdaQueryWrapper = new LambdaQueryWrapper<>();
        leaseReviewLambdaQueryWrapper.select(LeaseReview::getOrderId);

        if (StringUtils.isNotEmpty(orderReq.getOrderId())) {
            queryWrapper.eq(OrderBase::getOrderId, orderReq.getOrderId());
            return queryWrapper;
        }


        if (StringUtils.isNotEmpty(orderReq.getQueryTag())) {
            //姓名模糊查询
            cusQueryWrapper.like(Customer::getName, orderReq.getQueryTag());
            //电话模糊查询
            cusQueryWrapper.or().like(Customer::getPhone, orderReq.getQueryTag());
            //身份证模糊查询
            cusQueryWrapper.or().like(Customer::getIdNumber, orderReq.getQueryTag());
            //越秀合同编号模糊查询
            leaseReviewLambdaQueryWrapper.like(LeaseReview::getContractNumber, orderReq.getQueryTag());
        }

        if (StringUtils.isNotEmpty(orderReq.getOrderType())) {
            queryWrapper.eq(OrderBase::getType, orderReq.getOrderType());
        }
        //默认查询真租顶
        else {
            queryWrapper.eq(OrderBase::getType, DBConstants.BIZ_TYPE_ZZD);
        }

        //指定公司查询
        if (NullUtils.isNotNull(orderReq.getCompanyId())) {
            queryWrapper.eq(OrderBase::getCompanyId, orderReq.getCompanyId());
        }


        //按照越秀产品查询
        if (StringUtils.isNotEmpty(orderReq.getLeaseProductCode())) {
            queryWrapper.eq(OrderBase::getProductWithArea, orderReq.getLeaseProductCode());
        }

        //项目公司查询
        if (StringUtils.isNotEmpty(orderReq.getPrjCompanyId())) {
            queryWrapper.eq(OrderBase::getProjectCompany, orderReq.getPrjCompanyId());
        }

        //地址查询
        if (NullUtils.isNotNull(orderReq.getAddress())) {
            if (StringUtils.isNotEmpty(orderReq.getAddress().getProvinceCode())) {
                queryWrapper.eq(OrderBase::getProvinceCode, orderReq.getAddress().getProvinceCode());
                if (StringUtils.isNotEmpty(orderReq.getAddress().getCityCode())) {
                    queryWrapper.eq(OrderBase::getCityCode, orderReq.getAddress().getCityCode());
                    if (StringUtils.isNotEmpty(orderReq.getAddress().getAreaCode())) {
                        queryWrapper.eq(OrderBase::getAreaCode, orderReq.getAddress().getAreaCode());
                    }
                }
            }
            if (StringUtils.isNotEmpty(orderReq.getAddress().getInstallationAddress())) {
                queryWrapper.like(OrderBase::getInstallationAddress, orderReq.getAddress().getInstallationAddress());
            }
        }

        //阶段查询
        if (StringUtils.isNotEmpty(orderReq.getStageId())) {
            //统计要排除：终结、锁定、已完成的订单
            orderStateQueryWrapper
                    .eq(OrderState::getStageId, orderReq.getStageId());


            //查询全部的单，包括完结、锁定、终结的
            if (NullUtils.isNotEmpty(orderReq.getExcludeSpecialStateIds())) {
                List<String> excludeSpecialStateIds = new ArrayList<>(orderReq.getExcludeSpecialStateIds());
                //查询特殊状态时
                if (StringUtils.isNotEmpty(orderReq.getStateId())) {
                    excludeSpecialStateIds.remove(orderReq.getStateId());
                }

                Set<String> excludeSpecialStates = orderStateService.lambdaQuery()
                        .select(OrderState::getOrderId)
                        .in(OrderState::getStateId, excludeSpecialStateIds).list()
                        .stream().map(OrderState::getOrderId).collect(Collectors.toSet());

                //查询初设评审，屏蔽设计变更
                if (BizTaskEnum.TASK_CSPSXX.getTaskId().equals(orderReq.getTaskId())) {
                    Set<String> excludeTasks = orderStateService.lambdaQuery().eq(OrderState::getTaskId, BizTaskEnum.TASK_CSPSXX_UPDATE.getTaskId()).
                            list().stream().map(OrderState::getOrderId).collect(Collectors.toSet());
                    excludeSpecialStates.addAll(excludeTasks);
                }

                orderStateQueryWrapper.notIn(
                        NullUtils.isNotEmpty(excludeSpecialStates),
                        OrderState::getOrderId, excludeSpecialStates);
            }
        }

        //根据任务查询
        if (StringUtils.isNotEmpty(orderReq.getTaskId())) {
            orderStateQueryWrapper.eq(OrderState::getTaskId, orderReq.getTaskId());
        }

        //指定状态
        if (StringUtils.isNotEmpty(orderReq.getStateId())) {
            LinkedHashMap<String, BizTaskStateEnum> enumMap = EnumUtil.getEnumMap(BizTaskStateEnum.class);
            orderStateQueryWrapper.and(wrapper -> {
                if (enumMap.containsKey(orderReq.getStateId())) {
                    wrapper.eq(OrderState::getStateId, orderReq.getStateId());
                } else {
                    wrapper.like(OrderState::getStateId, orderReq.getStateId());
                }
                //需要排除的状态
                if (NullUtils.isNotEmpty(orderReq.getExcludeTaskStateIds())) {
                    wrapper.notIn(NullUtils.isNotEmpty(orderReq.getExcludeTaskStateIds()), OrderState::getStateId, orderReq.getExcludeTaskStateIds());
                }
            });
        } else {
            //按排除状态查询
            if (NullUtils.isNotEmpty(orderReq.getExcludeTaskStateIds())) {
                orderStateQueryWrapper.notIn(OrderState::getStateId, orderReq.getExcludeTaskStateIds());
            }
        }

        //按状态排序
        if (Boolean.TRUE.equals(orderReq.getSortByState())) {
            orderStateQueryWrapper.orderByAsc(OrderState::getSort);
        }
//                //没有指定状态
//                else {
//                    orderStateQueryWrapper.and( wrapper -> {
//                        wrapper.like(OrderState::getStateId, "WAITING").or()
//                                .like(OrderState::getStateId, Constants.REJECT);
//                    });
//                }

        //是否根据阶段任务状态查询
        boolean isSearchByStageTaskState = StringUtils.isNotEmpty(orderReq.getStageId()) ||
                StringUtils.isNotEmpty(orderReq.getTaskId()) || StringUtils.isNotEmpty(orderReq.getStateId());
        Set<String> stateList;
        if (isSearchByStageTaskState) {
            stateList = orderStateService.list(orderStateQueryWrapper).stream().map(OrderState::getOrderId).collect(Collectors.toSet());
            //没有符合状态的订单
            if (NullUtils.isEmpty(stateList)) {
                queryWrapper.isNull(OrderBase::getOrderId);
                return queryWrapper;
            }
            log.info("符合状态 {} {} {} 的订单列表数量{} \n{}", orderReq.getStageId(), orderReq.getTaskId(),
                    orderReq.getStateId(), stateList.size(), stateList);
        } else {
            stateList = new HashSet<>();
        }

        if (StringUtils.isNotEmpty(orderReq.getQueryTag())) {
            //越秀合同编号查询
            Set<String> leaseReviewOrderIds = leaseReviewService.list(leaseReviewLambdaQueryWrapper).stream().map(LeaseReview::getOrderId).collect(Collectors.toSet());
            stateList.addAll(leaseReviewOrderIds);
        }

        if (NullUtils.isNotEmpty(stateList) || StringUtils.isNotEmpty(orderReq.getQueryTag())) {
            queryWrapper.and(wrapper -> {
                wrapper.in(NullUtils.isNotEmpty(stateList), OrderBase::getOrderId, stateList).or();
                wrapper.like(StringUtils.isNotEmpty(orderReq.getQueryTag()), OrderBase::getOrderId, orderReq.getQueryTag()).or();
                wrapper.like(StringUtils.isNotEmpty(orderReq.getQueryTag()), OrderBase::getInstallationAddress, orderReq.getQueryTag());
            });
        }


        //没有按照客户信息查询,不查客户信息。提升性能
        if (StringUtils.isNotEmpty(orderReq.getQueryTag())) {
            val customerList = customerService.list(cusQueryWrapper);
            if (NullUtils.isNotEmpty(customerList)) {
                queryWrapper.in(NullUtils.isNotEmpty(customerList), OrderBase::getCustomerId, customerList.stream().map(Customer::getCustomerId).collect(Collectors.toSet()));
            }
        }

        if (Boolean.FALSE.equals(orderReq.getSortByState())) {
            queryWrapper.orderByDesc(OrderBase::getUpdateTime);
        }


        return queryWrapper;
    }


    /**
     * 判断施工组件是否都已填好
     */
    public boolean checkConstructDeviceZuJianFilledOk(String orderId) {
        val device = deviceService.lambdaQuery()
                .eq(Device::getOrderId, orderId)
                .eq(Device::getDeviceType, Constants.DEVICE_TYPE_ZUJIAN)
                .one();
        if (NullUtils.isNull(device)) {
            return false;
        }
        return device.getDeviceQuantity() == JSONArray.parseArray(device.getDeviceNumber()).size();
    }


    /**
     * 系统自动触发，推送承租人信息，越秀预审
     * 条件：1 业主信息-内审通过 2、踏勘信息-博通审核通过  3、技术勘察-博通审核通过
     */
//    @Transactional
    public void pushSyncProjectLeasePreApproval(String orderId) {
        val cusPassOrderState = btoOrderStateService.getOrderState(orderId, BizStageEnum.CUSTOMER_INFO.getStageId(),
                null, BizTaskStateEnum.APPROVAL_PASS.getStateId());
        val takanPassOrderState = btoOrderStateService.getOrderState(orderId, BizStageEnum.KAN_CHA.getStageId(),
                BizTaskEnum.TASK_TA_KAN.getTaskId(), BizTaskStateEnum.APPROVAL_PASS_BTO.getStateId());
        val tecKanChaPassOrderState = btoOrderStateService.getOrderState(orderId, BizStageEnum.KAN_CHA.getStageId(),
                BizTaskEnum.TASK_JSKC.getTaskId(), BizTaskStateEnum.APPROVAL_PASS_BTO.getStateId());

        if (NullUtils.isAnyNull(cusPassOrderState, takanPassOrderState, tecKanChaPassOrderState)) {
            log.info("系统触发自动推送越秀，承租人信息预审，相关内部数据未审核通过 业主信息状态 {} 踏勘状态 {}  技术勘察状态 {}", cusPassOrderState, takanPassOrderState, tecKanChaPassOrderState);
            return;
        }


        //推送越秀-进件风险审查-更新为待越秀审核状态
        val operatingRes = leaseApi.operating(orderService.getById(orderId));
        if (NullUtils.isNull(operatingRes)) {
            throw new BizException("推送越秀同步进件，风险审查失败，请重新操作。 订单 {}", orderId);
        }
        val isPushFile = leaseApi.isFileAndContactSyncPush(orderId, Constants.FXSC_FILE_LIST, true);
        if (!isPushFile) {
            throw new BizException("推送越秀同步进件的资料信息，风险审查失败，请重新操作。 订单 {}", orderId);
        }

        LeaseReview leaseReview = leaseReviewService.lambdaQuery()
                .eq(LeaseReview::getOrderId, orderId).one();
        if (NullUtils.isNull(leaseReview)) {
            leaseReview = new LeaseReview();
            leaseReview.setOrderId(orderId);
        }
        leaseReview.setBusinessKey(operatingRes.getBusinessKey());
        leaseReview.setContractNumber(operatingRes.getContractNumber());

        leaseReviewService.saveOrUpdate(leaseReview);

        //重置越秀审核状态记录
        btoLeaseReviewService.clearLeaseReviewState(orderId, Constants.AGAIN_SYNCPROJECT);

        //拒绝后-重复进件。必须要先提交创建，避免更新重复创建
        transactionTemplate.executeWithoutResult(transactionStatus ->
                leaseSyncProjectHandler.createNewInitState(orderId, BizStageEnum.LEASE_SYNC_PROJECT.getStageId(), null)
        );
        leaseSyncProjectHandler.updateToWaitingApprovalState(orderId, BizStageEnum.LEASE_SYNC_PROJECT.getStageId(), null);
    }


    private FormBtnsDto getFormBtns(String orderId, String stageId, String taskId, String... needPermission) {
        FormBtnsDto btns = new FormBtnsDto();
        btns.setHasEditBtn(btoUserService.isCurrentUserCanEditOrderInfo(orderId, stageId, taskId));
        boolean canApproval = btoUserService.isCurrentUserHasPermission(needPermission);
        btns.setHasApprovalBtn(canApproval);


        OrderState orderTaskState = btoOrderStateService.getOrderTaskState(orderId, stageId, taskId);
        //默认有就可以编辑
        btns.setCanEdit(btns.getHasEditBtn());
        //任务状态还没创建
        if (NullUtils.isNull(orderTaskState)) {
            btns.setCanApproval(false);
        }
        //待内审、待博通审 可以审核-不能编辑
        else if (orderTaskState.getStateId().contains(Constants.WAITING_APPROVAL)) {
            //待越秀审核 - 不能审核，不能编辑
            if (orderTaskState.getStateId().contains("LEASE")) {
                btns.setCanApproval(false);
                btns.setCanEdit(false);
                btns.setTips("等待资方审核");
            } else {
                btns.setCanApproval(true);
                btns.setCanEdit(false);
            }
        }
        //审核通过 无法编辑,无法审核
        else if (orderTaskState.getStateId().contains(Constants.PASS)) {
            btns.setCanEdit(false);
            btns.setCanApproval(false);
        }
        //拒绝状态
        else if (orderTaskState.getStateId().contains(Constants.REJECT)) {
            btns.setCanEdit(true);
            btns.setCanApproval(false);
        } else {
            btns.setCanApproval(false);
            btns.setTips("该任务:" + taskId + " 状态" + orderTaskState.getStateId() + "：无法审核");
        }

        //填充拒绝理由
        if (NullUtils.isNotNull(orderTaskState)) {
            LambdaQueryChainWrapper<OrderOperationLog> operationLogLambdaQueryChainWrapper = orderOperationLogService.lambdaQuery()
                    .eq(OrderOperationLog::getOrderId, orderId)
                    .eq(OrderOperationLog::getStageId, stageId).and(wrapper -> {
                        wrapper.like(OrderOperationLog::getStateId, Constants.REJECT)
                                .or().like(OrderOperationLog::getStateId, Constants.PASS);
                    });
            if (StringUtils.isEmpty(taskId)) {
                operationLogLambdaQueryChainWrapper.isNull(OrderOperationLog::getTaskId);
            } else {
                operationLogLambdaQueryChainWrapper.eq(OrderOperationLog::getTaskId, taskId);
            }
            OrderOperationLog reject = operationLogLambdaQueryChainWrapper
                    .orderByDesc(OrderOperationLog::getCreateTime)
                    .last("LIMIT 1").one();
            if (!NullUtils.isAnyNull(reject)) {
                if (StringUtils.isNotEmpty(reject.getApprovalInfo())) {
                    btns.setRejectReason(JSON.parseObject(reject.getApprovalInfo(), ApprovalReq.class));
                }
            } else {
                btns.setRejectReason(new ApprovalReq());
            }

            //待审核
            if (orderTaskState.getStateId().contains(Constants.WAITING_APPROVAL)) {
                if (!orderTaskState.getStateId().contains("LEASE")) {
                    btns.setRejectReason(new ApprovalReq());
                }
            }

        } else {
            btns.setRejectReason(new ApprovalReq());
        }


        return btns;
    }

    //有审核模块
    private FormBtnsDto getFormBtns(String orderId, String stageId, String taskId, EditAndApprovalEnum editAndApprovalEnum) {
        FormBtnsDto btns = new FormBtnsDto();
        //编辑按钮
        btns.setHasEditBtn(btoUserService.isCurrentUserCanEditOrderInfo(orderId, stageId, taskId, editAndApprovalEnum.getEditList()));
        //审核按钮
        btns.setHasApprovalBtn(btoUserService.isCurrentUserHasPermission(stageId, taskId, editAndApprovalEnum.getApprovalList()));

        OrderState orderTaskState = btoOrderStateService.getOrderTaskState(orderId, stageId, taskId);
        //默认有就可以编辑
        btns.setCanEdit(btns.getHasEditBtn());
        //任务状态还没创建
        if (NullUtils.isNull(orderTaskState)) {
            btns.setCanApproval(false);//不能审核
            btns.setCanApprovalModule(false);//不能填写审核内容
        }
        //待内审、待博通审 可以审核-不能编辑
        else if (orderTaskState.getStateId().contains(Constants.WAITING_APPROVAL)) {
            //待越秀审核 - 不能审核，不能编辑  -- 会显示审核模块的博通通过记录
            if (orderTaskState.getStateId().contains("LEASE")) {
                btns.setCanApproval(false);//不能审核
                btns.setCanEdit(false);//不能编辑
                btns.setCanApprovalModule(false);//不能填写审核内容
                btns.setHasApprovalModule(true);//可以显示博通审核通过的记录
                btns.setTips("等待资方审核");
            }
            //待博通审核 - 能审核，不能编辑
            else {
                btns.setCanEdit(false);//不能编辑
                btns.setCanApproval(true);//能审核
                btns.setHasApprovalModule(btns.getHasApprovalBtn());//有审核模块
                btns.setCanApprovalModule(btns.getHasApprovalBtn());//能填写审核模块
            }
        }
        //审核通过 无法编辑,无法审核
        else if (orderTaskState.getStateId().contains(Constants.PASS)) {
            btns.setCanEdit(false);
            btns.setCanApproval(false);
            btns.setCanApprovalModule(false);
            btns.setHasApprovalModule(true);
            //设计变更后还能变更
            if (BizStageEnum.DESIGN.getStageId().equals(stageId) && BizTaskEnum.TASK_CSPSXX_UPDATE.getTaskId().equals(taskId)) {
                btns.setCanEdit(true);
            }
        }
        //拒绝状态
        else if (orderTaskState.getStateId().contains(Constants.REJECT)) {
            btns.setCanEdit(true);//能编辑
            btns.setCanApproval(false);//不能审核
            btns.setCanApprovalModule(false);//没有填写审核模块
            btns.setHasApprovalModule(true);//显示审核拒绝模块
        }
        //待填写
        else {
            btns.setCanApproval(false);
            btns.setCanApprovalModule(false);
            btns.setHasApprovalModule(false);
            btns.setTips("该任务:" + taskId + " 状态" + orderTaskState.getStateId() + "：无法审核");
        }

        //填充理由
        if (NullUtils.isNotNull(orderTaskState)) {
            LambdaQueryChainWrapper<OrderOperationLog> operationLogLambdaQueryChainWrapper = orderOperationLogService.lambdaQuery()
                    .eq(OrderOperationLog::getOrderId, orderId)
                    .eq(OrderOperationLog::getStageId, stageId).and(wrapper -> {
                        wrapper.like(OrderOperationLog::getStateId, Constants.REJECT)
                                .or().like(OrderOperationLog::getStateId, Constants.PASS);
                    });
            if (StringUtils.isEmpty(taskId)) {
                operationLogLambdaQueryChainWrapper.isNull(OrderOperationLog::getTaskId);
            } else {
                operationLogLambdaQueryChainWrapper.eq(OrderOperationLog::getTaskId, taskId);
            }
            OrderOperationLog reject = operationLogLambdaQueryChainWrapper
                    .orderByDesc(OrderOperationLog::getCreateTime)
                    .last("LIMIT 1").one();

            if (!NullUtils.isAnyNull(reject)) {
                if (StringUtils.isNotEmpty(reject.getApprovalInfo())) {
                    btns.setRejectReason(JSON.parseObject(reject.getApprovalInfo(), ApprovalReq.class));
                }
            } else {
                btns.setRejectReason(new ApprovalReq());
            }
            //待审核
            if (orderTaskState.getStateId().contains(Constants.WAITING_APPROVAL)) {
                if (!orderTaskState.getStateId().contains("LEASE")) {
                    btns.setRejectReason(new ApprovalReq());
                }
            }
        } else {
            btns.setRejectReason(new ApprovalReq());
        }

        return btns;
    }


    /**
     * 生成订单号
     */
    private String generateOrderNo() {
        String timeNow = DateUtils.dateTimeNow("yyMMddHHmmSSS");
        return timeNow + IdUtils.nanoId(3, "0123456789".toCharArray());
    }

}
